/*
 * Copyright (c) 2007-2008, Thomas Krause (tho.krause@gmail.com)
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 *     * Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *     * Neither the name of gidoo nor the names of its contributors may be used to
 *       endorse or promote products derived from this software without specific
 *       prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.gidoo.cms.jcr;

import java.util.Calendar;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.gidoo.cms.GidooCMS;
import org.gidoo.cms.eventhandler.OnPublishPageEvent;
import org.gidoo.cms.helper.Tools;
import org.gidoo.cms.login.GidooCMSSession;

/**
 * Handle publishing of pages.
 * @author <a href="tho.krause@gmail.com">Thomas Krause</a>
 */
public class PublishDataManager 
{
  
  /**
   * Publish changes.
   * 
   * @param draft The draft node.
   * @param s The session.
   * 
   * @return True if successful.
   */
  public static boolean publishPageDraft(Node draft, GidooCMSSession s)
  {
    if(draft == null || s == null)
    {
      return false;
    }
    
    try
    {
      String path = Tools.draftName2Path(draft.getName());
      Node oldPublished = s.getJcrRootNode().getNode(path);

      // only save if non empty
      if(JcrHelper.isPublished(oldPublished))
      {
        oldPublished.checkin();
        oldPublished.checkout();
      }
      
      JcrHelper.copyPageProperties(draft, oldPublished);

      oldPublished.setProperty("cms:publisher", s.getUsername());

      oldPublished.checkout();

      draft.remove();

      s.getJcrRootNode().save();
            
      ((GidooCMS) s.getApplication()).getEventManager().fireEvent(
        new OnPublishPageEvent(path));
      
      return true;
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(GidooCMS.ERROR_LOG).log(Level.SEVERE, null, ex);
      s.error(getI18N(s).getString("jcrerror"));
    }
    
    return false;
  }
  
  /**
   * Reject a draft.
   * @param draft The draft.
   * @param s The session.
   * 
   * @return True if successful.
   */
  public static boolean rejectPageDraft(Node draft, GidooCMSSession s)
  {
    if(draft == null || s == null)
    {
      return false;
    }
    
    try
    {
      Node parent = draft.getParent();
      draft.remove();
      parent.save();
      return true;
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(GidooCMS.ERROR_LOG).log(Level.SEVERE, null, ex);
      s.error(getI18N(s).getString("jcrerror"));
    }
    
    return false;
  }

  /**
   * Publish a newly added ressource.
   * @param draft The newly added ressource.
   * @param s The session.
   * 
   * @return True if successful.
   */
  public static boolean  publishRessource(Node draft, GidooCMSSession s)
  {
    if(draft == null || s == null)
    {
      return false;
    }
    
    try
    {
      Session jcrSession = s.getJcrSession();
      String path = Tools.draftName2Path(draft.getName());
      if(s.getJcrRootNode().hasNode(path))
      {
        // ups, there is already a node with this path, delete the draft and
        // and inform the user
        s.warn(getI18N(s).getString("resexists"));
        Node parent = draft.getParent();
        draft.remove();
        parent.save();
        return false;
      }
      
      draft.setProperty("cms:publisher", s.getUsername());
      draft.setProperty("jcr:lastModified", Calendar.getInstance());
      
      jcrSession.move(draft.getPath(), "/" + path);
      jcrSession.save();
      
      return true;
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(GidooCMS.ERROR_LOG).log(Level.SEVERE, null, ex);
      s.error(getI18N(s).getString("jcrerror"));
    }
    
    return false;
  }
  
  /**
   * Rejectt a newly added ressource.
   * @param draft The newly added ressource.
   * @param s The session.
   * 
   * @return True if successful.
   */
  public static boolean rejectRessource(Node draft, GidooCMSSession s)
  {
    if(draft == null || s == null)
    {
      return false;
    }
    
    try
    {
      Node parent = draft.getParent();
      draft.remove();
      parent.save();
      
      return true;
    }
    catch(RepositoryException ex)
    {
      Logger.getLogger(GidooCMS.ERROR_LOG).log(Level.SEVERE, null, ex);
      s.error(getI18N(s).getString("jcrerror"));
    }
    
    return false;
  }
  
  private static ResourceBundle getI18N(GidooCMSSession session)
  {
    return java.util.ResourceBundle.getBundle("org/gidoo/cms/jcr/I18N", session.getLocale());
  }
  
}
